<template>
  <div class="service-management-edit">
    <el-card>
      <div class="card-header">
        <span>编辑服务</span>
      </div>
      
      <el-form v-if="serviceInfo" :model="serviceForm" :rules="rules" ref="serviceForm" label-width="120px">
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="serviceForm.serviceName" placeholder="请输入服务名称" maxlength="100"></el-input>
        </el-form-item>
        
        <el-form-item label="服务类型" prop="serviceTypeId">
          <el-select v-model="serviceForm.serviceTypeId" placeholder="请选择服务类型">
            <el-option v-for="type in serviceTypes" :key="type.id" :label="type.typeName" :value="type.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属设备" prop="deviceId">
          <el-select v-model="serviceForm.deviceId" placeholder="请选择所属设备">
            <el-option v-for="device in devices" :key="device.id" :label="device.deviceName" :value="device.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="服务状态" prop="status">
          <el-select v-model="serviceForm.status" placeholder="请选择服务状态">
            <el-option label="运行中" value="RUNNING"></el-option>
            <el-option label="已停止" value="STOPPED"></el-option>
            <el-option label="错误" value="ERROR"></el-option>
            <el-option label="置备中" value="PROVISIONING"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="serviceForm.description" placeholder="请输入描述信息" type="textarea" maxlength="500" show-word-limit></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
      
      <div v-else class="loading-container">
        <el-loading v-loading="true" element-loading-text="加载中..." style="min-height: 300px;"></el-loading>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ServiceManagementEdit',
  data() {
    return {
      serviceInfo: null,
      serviceForm: {
        id: '',
        serviceName: '',
        serviceTypeId: '',
        deviceId: '',
        status: 'RUNNING',
        description: ''
      },
      originalDeviceId: '',
      serviceTypes: [],
      devices: [],
      rules: {
        serviceName: [
          { required: true, message: '请输入服务名称', trigger: 'blur' },
          { max: 100, message: '服务名称不能超过100个字符', trigger: 'blur' }
        ],
        serviceTypeId: [
          { required: true, message: '请选择服务类型', trigger: 'change' }
        ],
        deviceId: [
          { required: true, message: '请选择所属设备', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择服务状态', trigger: 'change' }
        ],
        description: [
          { max: 500, message: '描述信息不能超过500个字符', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    const serviceId = this.$route.query.id;
    if (serviceId) {
      this.loadServiceInfo(serviceId);
    } else {
      this.$message.error('服务ID不能为空');
      this.$router.push('/service-management');
    }
  },
  methods: {
    loadServiceInfo(serviceId) {
      this.$api.syncTaskApi.getById(serviceId)
        .then(res => {
          this.serviceInfo = res && res.data || null;
          if (this.serviceInfo) {
            this.originalDeviceId = this.serviceInfo.deviceId;
            // 填充表单数据
            this.serviceForm = {
              id: this.serviceInfo.id,
              serviceName: this.serviceInfo.serviceName,
              serviceTypeId: this.serviceInfo.serviceTypeId,
              deviceId: this.serviceInfo.deviceId,
              status: this.serviceInfo.status,
              description: this.serviceInfo.description || ''
            };
            // 加载服务类型和设备列表
            this.loadServiceTypes();
            this.loadDevices();
          } else {
            this.$message.error('获取服务信息失败');
            this.$router.push('/service-management');
          }
        })
        .catch(error => {
          console.error('获取服务信息失败:', error);
          this.$message.error('获取服务信息失败: ' + error.message);
          this.$router.push('/service-management');
        });
    },
    
    loadServiceTypes() {
      this.$api.serviceTypeApi.getAll()
        .then(res => {
          this.serviceTypes = res && res.data || [];
        })
        .catch(error => {
          console.error('获取服务类型失败:', error);
          this.$message.error('获取服务类型失败');
        });
    },
    
    loadDevices() {
      this.$api.deviceApi.getAll()
        .then(res => {
          this.devices = res && res.data || [];
        })
        .catch(error => {
          console.error('获取设备列表失败:', error);
          this.$message.error('获取设备列表失败');
        });
    },
    
    handleSubmit() {
      this.$refs.serviceForm.validate((valid) => {
        if (valid) {
          // 检查服务名称在同一设备下是否已存在（如果设备发生变化）
          if (this.serviceForm.deviceId !== this.originalDeviceId) {
            this.$api.syncTaskApi.getAll({
              serviceName: this.serviceForm.serviceName,
              deviceId: this.serviceForm.deviceId
            }).then(res => {
              const services = res && res.data || [];
              const exists = services.some(service => 
                service.serviceName === this.serviceForm.serviceName && 
                service.deviceId === this.serviceForm.deviceId &&
                service.id !== this.serviceForm.id
              );
              
              if (exists) {
                this.$message.error('该设备下已存在同名服务');
                return;
              }
              
              this.submitForm();
            }).catch(error => {
              console.error('检查服务名称失败:', error);
              this.submitForm();
            });
          } else {
            this.submitForm();
          }
        }
      });
    },
    
    submitForm() {
      // 提交表单
      this.$api.syncTaskApi.update(this.serviceForm.id, this.serviceForm)
        .then(() => {
          this.$message.success('服务更新成功');
          this.$router.push('/service-management');
        })
        .catch(error => {
          console.error('更新服务失败:', error);
          this.$message.error('更新服务失败: ' + error.message);
        });
    },
    
    handleCancel() {
      this.$router.push('/service-management');
    }
  }
};
</script>

<style scoped>
.service-management-edit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.loading-container {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>